

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cai Shibo">
  <meta name="keywords" content="cc">
  
    <meta name="description" content="Mybatis简介原始 jdbc 开发存在如下问题：  数据库连接创建、释放频繁，造成系统资源浪费从而影响系统性能。 sql 语句在代码中硬编码，造成代码不易维护，实际应用 sql 变化可能较大，sql 变动需要改变 java 代码。 查询操作时，需要将结果集中的数据手动封装到实体中。插入操作时，需要手动将实体数据设置到 sql 语句的占位符位置。  因此给出解决方案：  使用数据库连接池初始化连">
<meta property="og:type" content="article">
<meta property="og:title" content="SSM--D11">
<meta property="og:url" content="https://hahsx_xd.gitee.io/2022/05/02/SSM-D11/index.html">
<meta property="og:site_name" content="🍊CAI SHIBO🥬">
<meta property="og:description" content="Mybatis简介原始 jdbc 开发存在如下问题：  数据库连接创建、释放频繁，造成系统资源浪费从而影响系统性能。 sql 语句在代码中硬编码，造成代码不易维护，实际应用 sql 变化可能较大，sql 变动需要改变 java 代码。 查询操作时，需要将结果集中的数据手动封装到实体中。插入操作时，需要手动将实体数据设置到 sql 语句的占位符位置。  因此给出解决方案：  使用数据库连接池初始化连">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://hahsx_xd.gitee.io/images/pasted-118.png">
<meta property="og:image" content="https://hahsx_xd.gitee.io/images/pasted-120.png">
<meta property="og:image" content="https://hahsx_xd.gitee.io/images/pasted-121.png">
<meta property="og:image" content="https://hahsx_xd.gitee.io/images/pasted-119.png">
<meta property="og:image" content="https://hahsx_xd.gitee.io/images/pasted-122.png">
<meta property="article:published_time" content="2022-05-02T01:53:06.000Z">
<meta property="article:modified_time" content="2022-11-29T07:14:46.500Z">
<meta property="article:author" content="Cai Shibo">
<meta property="article:tag" content="cc">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://hahsx_xd.gitee.io/images/pasted-118.png">
  
  
  <title>SSM--D11 - 🍊CAI SHIBO🥬</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"hahsx_xd.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":".|","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"#"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":5},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":true,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="🍊CAI SHIBO🥬" type="application/atom+xml">
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>^_^ 🥬 CC</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="SSM--D11">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      Cai Shibo
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-05-02 09:53" pubdate>
        2022年5月2日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      11k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      54 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">SSM--D11</h1>
            
              <p class="note note-info">
                
                  最后更新：23 天前
                
              </p>
            
            <div class="markdown-body">
              <h3 id="Mybatis"><a href="#Mybatis" class="headerlink" title="Mybatis"></a>Mybatis</h3><h4 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h4><p>原始 jdbc 开发存在如下问题：</p>
<ol>
<li>数据库连接创建、释放频繁，造成系统资源浪费从而影响系统性能。</li>
<li>sql 语句在代码中硬编码，造成代码不易维护，实际应用 sql 变化可能较大，sql 变动需要改变 java 代码。</li>
<li>查询操作时，需要将结果集中的数据手动封装到实体中。插入操作时，需要手动将实体数据设置到 sql 语句的占位符位置。</li>
</ol>
<p>因此给出解决方案：</p>
<ol>
<li>使用数据库连接池初始化连接资源。</li>
<li>将 sql 语句抽取到 xml 配置文件中。</li>
<li>使用反射、内省等底层技术。自动将实体与表进行属性与字段的自动映射。</li>
</ol>
<hr>
<h4 id="开发步骤"><a href="#开发步骤" class="headerlink" title="开发步骤"></a>开发步骤</h4><ol>
<li>添加 Mybatis 坐标</li>
</ol>
<p><strong>pom.xml（相关坐标）</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mybatis<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mybatis<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.5.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<ol start="2">
<li><p>创建 user 数据表</p>
</li>
<li><p>编写 User 实体类</p>
</li>
<li><p>编写映射文件 UserMapper.xml，映射配置文件，用于提取 sql 语句</p>
</li>
</ol>
<p><strong>resources/com/mapper/UserMapper.xml</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">mapper</span></span><br><span class="hljs-meta">        <span class="hljs-meta-keyword">PUBLIC</span> <span class="hljs-meta-string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span><br><span class="hljs-meta">        <span class="hljs-meta-string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span><br><span class="hljs-comment">&lt;!--namespace命名空间--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">&quot;userMapper&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;findAll&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;com.domain.User&quot;</span>&gt;</span><br>        select * from user<br>    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<ol start="5">
<li>编写核心文件 SqlMapConfig.xml，核心配置文件  </li>
</ol>
<p><strong>SqlMapConfig.xml</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">configuration</span></span><br><span class="hljs-meta">        <span class="hljs-meta-keyword">PUBLIC</span> <span class="hljs-meta-string">&quot;-//mybatis.org//DTD Config 3.0//EN&quot;</span></span><br><span class="hljs-meta">        <span class="hljs-meta-string">&quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span><br>    <span class="hljs-comment">&lt;!--数据源环境--&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">environments</span> <span class="hljs-attr">default</span>=<span class="hljs-string">&quot;developement&quot;</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">environment</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;developement&quot;</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">transactionManager</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;JDBC&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">transactionManager</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">dataSource</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;POOLED&quot;</span>&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;driver&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;com.mysql.jdbc.Driver&quot;</span>/&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;url&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>/&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;username&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;root&quot;</span>/&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;password&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;csx011122&quot;</span>/&gt;</span><br>            <span class="hljs-tag">&lt;/<span class="hljs-name">dataSource</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">environment</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">environments</span>&gt;</span><br>    <span class="hljs-comment">&lt;!--加载映射文件--&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">&quot;com/mapper/UserMapper.xml&quot;</span>/&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span> <br><span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<ol start="6">
<li>调用</li>
</ol>
<p><strong>MyBatisTest.java</strong></p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MybatisTest</span> </span>&#123;<br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test1</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        <span class="hljs-comment">//获得核心配置文件</span><br>        InputStream resourceAsStream = Resources.getResourceAsStream(<span class="hljs-string">&quot;sqlMapConfig.xml&quot;</span>);<br>        <span class="hljs-comment">//获得session工厂对象</span><br>        SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(resourceAsStream);<br>        <span class="hljs-comment">//获得session回话对象</span><br>        SqlSession sqlSession = sqlSessionFactory.openSession();<br>        <span class="hljs-comment">//执行操作 参数: namespace + id</span><br>        List&lt;User&gt; userList = sqlSession.selectList(<span class="hljs-string">&quot;userMapper.findAll&quot;</span>);<br>        System.out.println(userList);<br>        <span class="hljs-comment">//释放资源</span><br>        sqlSession.close();<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<h5 id="插入操作"><a href="#插入操作" class="headerlink" title="插入操作"></a>插入操作</h5><p><strong>UserMapper.xml（相关配置）</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--插入操作--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">insert</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;save&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;com.domain.User&quot;</span>&gt;</span><br>    <span class="hljs-comment">&lt;!--id, username等参数是实体类User的内部属性, 而非数据库中表的名称--&gt;</span><br>    insert into user values(#&#123;id&#125;, #&#123;username&#125;, #&#123;password&#125;)<br><span class="hljs-tag">&lt;/<span class="hljs-name">insert</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<p><strong>MtbatisTest.java（相关方法）</strong></p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test2</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>    User user = <span class="hljs-keyword">new</span> User();<br>    user.setUsername(<span class="hljs-string">&quot;mike&quot;</span>);<br>    user.setPassword(<span class="hljs-string">&quot;123456&quot;</span>);<br><br>    <span class="hljs-comment">//获得核心配置文件</span><br>    InputStream resourceAsStream = Resources.getResourceAsStream(<span class="hljs-string">&quot;sqlMapConfig.xml&quot;</span>);<br>    <span class="hljs-comment">//获得session工厂对象</span><br>    SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(resourceAsStream);<br>    <span class="hljs-comment">//获得session回话对象</span><br>    SqlSession sqlSession = sqlSessionFactory.openSession();<br>    <span class="hljs-comment">//执行操作 参数: namespace + id</span><br>    sqlSession.insert(<span class="hljs-string">&quot;userMapper.save&quot;</span>, user);<br>    <span class="hljs-comment">//MyBatis执行增删改的更新操作，需要提交事务</span><br>    sqlSession.commit();<br>    <span class="hljs-comment">//释放资源</span><br>    sqlSession.close();<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="MyBatis映射文件概述"><a href="#MyBatis映射文件概述" class="headerlink" title="MyBatis映射文件概述"></a>MyBatis映射文件概述</h4><p><img src="/images/pasted-118.png" srcset="/img/loading.gif" lazyload alt="UserMapper.xml"></p>
<hr>
<h4 id="MyBatis核心配置文件"><a href="#MyBatis核心配置文件" class="headerlink" title="MyBatis核心配置文件"></a>MyBatis核心配置文件</h4><ul>
<li>configuration（配置），以下为 configuration 标签下的子标签：<ul>
<li>properties（属性）</li>
<li>settings（设置）</li>
<li>typeAliases（类型别名）</li>
<li>typeHandlers（类型处理器）</li>
<li>objectFactory（对象工厂）</li>
<li>plugins（插件）</li>
<li>environments（环境）<ul>
<li>environment（环境变量）<ul>
<li>transactionManager（事务管理器）</li>
<li>dataSource（数据源）</li>
</ul>
</li>
</ul>
</li>
<li>databaseIdProvider（数据库厂商标识）</li>
<li>mappers（映射器）</li>
</ul>
</li>
</ul>
<p><strong>各标签的顺序不要混乱</strong>，如 typeAliases 如果放在最后就会出错。</p>
<hr>
<ol>
<li>properties（属性）  </li>
</ol>
<p><strong>实际开发中，习惯将数据源的配置信息单独抽取成一个 properties 文件，该标签可以加载额外配置的 properties 文件。</strong><br><img src="/images/pasted-120.png" srcset="/img/loading.gif" lazyload></p>
<ol start="2">
<li><p>typeAliases（类型别名）<br>MyBatis 框架已经设置好了一些常用的类型别名，如 String 别名 string，Long 别名 long，Integer 别名 int ……<br>此外，可以使用 typeAliases 标签自定义别名<br><img src="/images/pasted-121.png" srcset="/img/loading.gif" lazyload></p>
</li>
<li><p>typeHandlers（类型处理器）<br>MyBatis 在预处理语句中设置参数或从结果集中取出值，都会<strong>用类型处理器将获取的值以合适的方式转换成 Java 类型</strong>。  </p>
<ul>
<li>BooleanTypeHandler：Java.lang.Boolean.boolean –&gt; 数据库兼容的 BOOLEAN</li>
<li>ByteTypeHandler：Java.lang.Byte.byte –&gt; 数据库兼容的 NUMERIC 或 BYTE</li>
<li>IntegerTypeHandler：Java.lang.Integer.int –&gt; 数据库兼容的 NUMERIC 或 INTEGER</li>
<li>……………….  </li>
</ul>
</li>
</ol>
<p> 如果预设的类型处理器不满足业务需求，可以<strong>重写类型处理器或创建自定义的类型处理器</strong>来处理不支持的或非标准的类型。  </p>
<p> 具体做法：<strong>实现 org.apache.ibatis.type.TypeHandler 接口或继承 org.apache.ibatis.type.BaseTypeHandler 类，然后选择性的将它映射到一个 JDBC 类型</strong>。  </p>
<p> 开发步骤：</p>
<ol>
<li>定义转换类继承类 BaseTypeHandler&lt; T &gt;</li>
<li>覆盖 4 个未实现的方法，其中 setNonNullParameter 为 Java 程序设置数据到数据库的回调方法，getNullableResult 为查询时 MySQL 的字符串类型转换成 Java 的 Type 类型的方法  </li>
</ol>
<p> <strong>DateTypeHandler.java</strong><br>      <figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DateTypeHandler</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseTypeHandler</span>&lt;<span class="hljs-title">Date</span>&gt; </span>&#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-comment">//将Java类型 转换成 数据库需要的类型</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setNonNullParameter</span><span class="hljs-params">(PreparedStatement preparedStatement, <span class="hljs-keyword">int</span> i, Date date, JdbcType jdbcType)</span> <span class="hljs-keyword">throws</span> SQLException </span>&#123;<br>        <span class="hljs-keyword">long</span> time = date.getTime();<br>        <span class="hljs-comment">//将预处理语句中的第i个参数的值改为time</span><br>        preparedStatement.setLong(i,time);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-comment">//将数据库类型 转换成 Java类型</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Date <span class="hljs-title">getNullableResult</span><span class="hljs-params">(ResultSet resultSet, String s)</span> <span class="hljs-keyword">throws</span> SQLException </span>&#123;<br>        <span class="hljs-comment">//获得结果集resultSet中 名称为s的字段 就是要进行类型转换的对象</span><br>        <span class="hljs-keyword">long</span> aLong = resultSet.getLong(s);<br>        Date date = <span class="hljs-keyword">new</span> Date(aLong);<br>        <span class="hljs-keyword">return</span> date;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-comment">//将数据库类型 转换成 Java类型</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Date <span class="hljs-title">getNullableResult</span><span class="hljs-params">(ResultSet resultSet, <span class="hljs-keyword">int</span> i)</span> <span class="hljs-keyword">throws</span> SQLException </span>&#123;<br>        <span class="hljs-comment">//获得结果集resultSet中 行数为i的字段 就是要进行类型转换的对象</span><br>        <span class="hljs-keyword">long</span> aLong = resultSet.getLong(i);<br>        Date date = <span class="hljs-keyword">new</span> Date(aLong);<br>        <span class="hljs-keyword">return</span> date;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-comment">//将数据库类型 转换成 Java类型</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Date <span class="hljs-title">getNullableResult</span><span class="hljs-params">(CallableStatement callableStatement, <span class="hljs-keyword">int</span> i)</span> <span class="hljs-keyword">throws</span> SQLException </span>&#123;<br>        <span class="hljs-comment">//获得存储过程callableStatement 下标为i的参数 就是要进行类型转换的对象</span><br>        <span class="hljs-keyword">long</span> aLong = callableStatement.getLong(i);<br>        Date date = <span class="hljs-keyword">new</span> Date(aLong);<br>        <span class="hljs-keyword">return</span> date;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure></p>
<ol start="3">
<li>在 MyBatis 核心配置文件中进行注册  </li>
</ol>
<p> <strong>sqlMapConfig.xml</strong><br> <figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">typeHandlers</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">typeHandler</span> <span class="hljs-attr">handler</span>=<span class="hljs-string">&quot;com.handler.DateTypeHandler&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">typeHandlers</span>&gt;</span><br></code></pre></div></td></tr></table></figure></p>
<ol start="4">
<li>plugins（插件）<br>MyBatis 可以使用第三方的插件来<strong>对功能进行扩展</strong>。  </li>
</ol>
<p> PageHelper（分页助手）将分页的复杂操作进行封装，使用简单的方式即可获得分页的相关数据。<br> 开发步骤：</p>
<ol>
<li>导入通用 PageHelper 的坐标  </li>
</ol>
<p> <strong>pom.xml</strong><br>  <figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.maven.plugins<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-war-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.3.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span><br>  <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span><br></code></pre></div></td></tr></table></figure></p>
<ol start="2">
<li><p>在 MyBatis 核心配置文件中配置 PageHelper插件</p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--配置分页助手插件--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span> <span class="hljs-attr">interceptor</span>=<span class="hljs-string">&quot;com.github.pagehelper.PageHelper&quot;</span>&gt;</span><br>        <span class="hljs-comment">&lt;!--指定方言--&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;dialect&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;mysql&quot;</span>/&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span><br></code></pre></div></td></tr></table></figure></li>
<li><p>获取分页数据</p>
  <figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testPageHelper</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>    InputStream resourceAsStream = Resources.getResourceAsStream(<span class="hljs-string">&quot;sqlMapConfig.xml&quot;</span>);<br>    SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(resourceAsStream);<br>    SqlSession sqlSession = sqlSessionFactory.openSession();<br>    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);<br><br>    <span class="hljs-comment">//设置分页相关参数  当前页 + 每页显示的条数</span><br>    PageHelper.startPage(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);<br>    List&lt;User&gt; users = userMapper.findAll();<br>    System.out.println(users);<br><br>	<span class="hljs-comment">//获得与分页相关参数</span><br>    PageInfo&lt;User&gt; pageInfo = <span class="hljs-keyword">new</span> PageInfo&lt;&gt;(users);<br>    System.out.println(<span class="hljs-string">&quot;当前页：&quot;</span> + pageInfo.getPageNum());<br>    System.out.println(<span class="hljs-string">&quot;上一页：&quot;</span> + pageInfo.getPrePage());<br>    System.out.println(<span class="hljs-string">&quot;下一页：&quot;</span> + pageInfo.getNextPage());<br>    System.out.println(<span class="hljs-string">&quot;每页显示条数：&quot;</span> + pageInfo.getPageSize());<br>    System.out.println(<span class="hljs-string">&quot;总页数：&quot;</span> + pageInfo.getPages());<br>    System.out.println(<span class="hljs-string">&quot;总条数：&quot;</span> + pageInfo.getTotal());<br>    System.out.println(<span class="hljs-string">&quot;是否是第一页：&quot;</span> + pageInfo.isIsFirstPage());<br>    System.out.println(<span class="hljs-string">&quot;是否是最后一页：&quot;</span> + pageInfo.isIsLastPage());<br><br>    sqlSession.close();<br>&#125;<br></code></pre></div></td></tr></table></figure></li>
<li><p>environments（环境）<br><img src="/images/pasted-119.png" srcset="/img/loading.gif" lazyload alt="environments（环境）"></p>
<ul>
<li>transactionManager（事务管理器）：<ul>
<li>JDBC：直接使用 JDBC 的提交和回滚设置，依赖于从数据源得到的连接来管理事务作用域。</li>
<li>MANAGED：这个配置几乎不做什么，从不提交或回滚事务，而是让容器来管理事务的整个生命周期（比如 JEE 应用服务器的上下文）。默认情况下它会关闭连接，然而一些容器并不希望这样，因此需要将 closeConnection 属性设置为 false 来阻止他默认的关闭行为。</li>
</ul>
</li>
<li>dataSource（数据源）：<ul>
<li>UNPOOLED：每次被请求都进行打开和关闭连接。</li>
<li>POOLED：利用 “池” 的概念将 JDBC 连接对象组织起来。</li>
<li>JNDI：为了能在如 EJB 或应用服务器这类容器中使用，容器可以集中或在外部配置数据源，然后放置一个 JNID 上下文的引用。</li>
</ul>
</li>
</ul>
</li>
<li><p>mappers（映射器）<br>用于加载映射，有如下几种方式：</p>
</li>
</ol>
<ul>
<li>使用相对类路径的资源引用</li>
<li>使用完全限定资源定位父（URL）</li>
<li>使用映射器接口实现类的完全限定类名</li>
<li>将包内的映射器接口实现全部注册为映射器</li>
</ul>
<hr>
<h4 id="MyBatis-相应-API"><a href="#MyBatis-相应-API" class="headerlink" title="MyBatis 相应 API"></a>MyBatis 相应 API</h4><h5 id="SqlSessionFactoryBuilder（SqlSession工厂构建器）"><a href="#SqlSessionFactoryBuilder（SqlSession工厂构建器）" class="headerlink" title="SqlSessionFactoryBuilder（SqlSession工厂构建器）"></a>SqlSessionFactoryBuilder（SqlSession工厂构建器）</h5><p>常用 API：SqlSessionFactory build(InputStream inputStream)  </p>
<p>作用：<strong>通过加载 mybatis 的核心文件的输入流的形式构建一个 SqlSessionFactory 对象</strong></p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-comment">//指定配置文件加载路径</span><br>String resource = <span class="hljs-string">&quot;sqlMapConfig.xml&quot;</span>;<br><span class="hljs-comment">//获得核心配置文件</span><br><span class="hljs-comment">//其中的 Resources 工具类，在 org.apache.ibatis.io 包中该类实现从类路径、文件系统或 webURL 中加载资源文件</span><br>InputStream resourceAsStream = Resources.getResourceAsStream(resource);<br><span class="hljs-comment">//new一个SqlSession工厂构建器；调用build方法，获得session工厂对象</span><br>SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(resourceAsStream);<br></code></pre></div></td></tr></table></figure>

<h5 id="SqlSessionFactory（SqlSession工厂对象）"><a href="#SqlSessionFactory（SqlSession工厂对象）" class="headerlink" title="SqlSessionFactory（SqlSession工厂对象）"></a>SqlSessionFactory（SqlSession工厂对象）</h5><p>SqlSessionFactory 有多个创建 SqlSession 实例的方法。常用的有如下两个：</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>解释</th>
</tr>
</thead>
<tbody><tr>
<td>openSession()</td>
<td>默认开启一个事务，但<strong>事务不会自动提交，需要手动提交该事务，更新操作才会持久化道数据库中</strong></td>
</tr>
<tr>
<td>openSession(boolean autoCommit)</td>
<td>参数 autoCommit 为是否提交，如果设置为 true，则自动提交，无需手动提交</td>
</tr>
</tbody></table>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-comment">//获得session会话对象，不自动提交</span><br>SqlSession sqlSession = sqlSessionFactory.openSession();<br><span class="hljs-comment">//手动提交事务</span><br>sqlSession.commit();<br><span class="hljs-comment">/*-------------------------------------*/</span><br><br><span class="hljs-comment">//获得session会话对象，自动提交</span><br>SqlSession sqlSession = sqlSessionFactory.openSession(<span class="hljs-keyword">true</span>);<br><span class="hljs-comment">//无需 commit() 手动提交事务</span><br></code></pre></div></td></tr></table></figure>

<h5 id="SqlSession会话对象"><a href="#SqlSession会话对象" class="headerlink" title="SqlSession会话对象"></a>SqlSession会话对象</h5><p>SqlSession 实例在 MyBatis 中是一个非常强大的类，包含所有执行语句、提交、回滚事务和获取映射器实例的方法。  </p>
<p><strong>执行语句的主要方法有：</strong></p>
<ul>
<li><T> T selectOne(String statement, Object parameter)</li>
<li><E> List<E> selectList(String statement, Object parameter)</li>
<li>int insert(String statement, Object parameter)</li>
<li>int update(String statement, Object parameter)</li>
<li>int delete(String statement, Object parameter)</li>
</ul>
<p><strong>操作事务的主要方法有：</strong></p>
<ul>
<li>void commit()</li>
<li>void rollback()</li>
</ul>
<hr>
<h4 id="MyBatis的Dao层实现–传统方式"><a href="#MyBatis的Dao层实现–传统方式" class="headerlink" title="MyBatis的Dao层实现–传统方式"></a>MyBatis的Dao层实现–传统方式</h4><ol>
<li>Dao 层使用配置的 MyBatis  </li>
</ol>
<p><strong>UserMapperImpl.java（在 Dao 层）</strong></p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserMapper</span> </span>&#123;<br>    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">findAll</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException</span>;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<ol start="2">
<li>和之前的传统项目类似，Service 层负责业务逻辑设计，Controller 层负责业务流程控制。</li>
</ol>
<hr>
<h4 id="MyBatis的Dao层实现–代理方式"><a href="#MyBatis的Dao层实现–代理方式" class="headerlink" title="MyBatis的Dao层实现–代理方式"></a>MyBatis的Dao层实现–代理方式</h4><p>采用 MyBatis 的代理开发方式实现 Dao 层的开发，符合当前主流。<br>Mapper 接口开发方式只需要程序员编写 Mapper 接口（相当于 Dao 接口），由 MyBatis 框架根据接口定义创建接口的动态代理对象，代理对象的方法体痛上边 Dao 接口实现类方法。<br>Mapper 接口开发要遵守以下规范：</p>
<ol>
<li>Mapper.xml 文件中的 namespace 与 mapper 接口的全限定名相同，即<strong>根源开始的引用路径</strong></li>
<li>Mapper 接口方法名和 Mapper.xml 中定义的每个 statement 的 id 相同</li>
<li>Mapper 接口方法的输入参数类型和 mapper.xml 中定义的每个 sql 的 parameterType 的类型相同</li>
<li>Mapper 接口方法的输出参数类型和 mapper.xml 中定义的每个 sql 的 resultType 的类型相同</li>
</ol>
<p><strong>注意：namespace 、 parameterType 与 resultType 都需要与方法接口相同，namespace 与 mapper 接口的根源引用路径相同；参数也同理。</strong><br><img src="/images/pasted-122.png" srcset="/img/loading.gif" lazyload></p>
<hr>
<h4 id="动态sql语句"><a href="#动态sql语句" class="headerlink" title="动态sql语句"></a>动态sql语句</h4><p>实际业务的需求往往更加复杂，因此 sql 语句也是多样的，为了不配置大量的 sql 语句，使用灵活的动态 sql 语句。</p>
<ul>
<li>if  </li>
</ul>
<p><strong>UserMapper.xml（相关配置）</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;findByCondition&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;user&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span><br>    select * from user<br>    <span class="hljs-tag">&lt;<span class="hljs-name">where</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;id!=0&quot;</span>&gt;</span><br>            and id = #&#123;id&#125;<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;username!=null&quot;</span>&gt;</span><br>            and username = #&#123;username&#125;<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">if</span> <span class="hljs-attr">test</span>=<span class="hljs-string">&quot;password!=null&quot;</span>&gt;</span><br>            and password = #&#123;password&#125;<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">if</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">where</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<ul>
<li>foreach</li>
</ul>
<p><strong>UserMapper.xml（相关配置）</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;findByIds&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;list&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span><br>    select * from user<br>    <span class="hljs-tag">&lt;<span class="hljs-name">where</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">foreach</span> <span class="hljs-attr">collection</span>=<span class="hljs-string">&quot;list&quot;</span> <span class="hljs-attr">open</span>=<span class="hljs-string">&quot;id in(&quot;</span> <span class="hljs-attr">close</span>=<span class="hljs-string">&quot;)&quot;</span> <span class="hljs-attr">item</span>=<span class="hljs-string">&quot;id&quot;</span> <span class="hljs-attr">separator</span>=<span class="hljs-string">&quot;,&quot;</span>&gt;</span><br>            #&#123;id&#125;<br>        <span class="hljs-tag">&lt;/<span class="hljs-name">foreach</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">where</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<hr>
<h5 id="动态sql语句抽取"><a href="#动态sql语句抽取" class="headerlink" title="动态sql语句抽取"></a>动态sql语句抽取</h5><figure class="highlight xml"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">sql</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;selectUser&quot;</span>&gt;</span>select * from user<span class="hljs-tag">&lt;/<span class="hljs-name">sql</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;findByCondition&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;user&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">include</span> <span class="hljs-attr">refid</span>=<span class="hljs-string">&quot;selectUser&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">include</span>&gt;</span><br>    <span class="hljs-comment">&lt;!--等同于语句select * from user--&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br></code></pre></div></td></tr></table></figure>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章未经允许，严禁转载！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/05/02/SSM-D12/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">SSM--D12</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/05/01/SSM-D10/">
                        <span class="hidden-mobile">SSM--D10</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     CC <i class="iconfont icon-love"></i> XX
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    
      <script  src="/js/img-lazyload.js" ></script>
    
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
